package kr.couponplay.android.activity;

import java.io.File;
import java.util.Calendar;

import kr.couponplay.android.AppContext;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

@SuppressLint("HandlerLeak") 
public class BackPressActivity extends BaseActivity {
	private static final int MSG_TIMER_EXPIRED = 1;
	private static final int BACKKEY_TIMEOUT = 2;
	private static final int MILLIS_IN_SEC = 1000;
	
	private boolean isBackKeyPressed = false;
	private long currTimeInMillis = 0;
	
    @Override
    public void onBackPressed() {
    	if (isBackKeyPressed == false) {
    		isBackKeyPressed = true;
    		currTimeInMillis = Calendar.getInstance().getTimeInMillis();
    		Toast.makeText(this, "'뒤로' 버튼을 한번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
    		startTimer();
	    } else {
	    	isBackKeyPressed = false;
	    	if (Calendar.getInstance().getTimeInMillis() <= (currTimeInMillis + (BACKKEY_TIMEOUT * MILLIS_IN_SEC))) {
	    		finish();
	    		AppContext.clear();
	    		ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
	    		activityManager.restartPackage(getPackageName());
	    	}
	    }
    }
     
    private void startTimer() {
    	mTimerHandler.sendEmptyMessageDelayed(MSG_TIMER_EXPIRED, BACKKEY_TIMEOUT * MILLIS_IN_SEC);
    }
     
    private Handler mTimerHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
    			case MSG_TIMER_EXPIRED: {
    				isBackKeyPressed = false;
    			}
    			break;
    		}
    	}
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        clearApplicationCache(getCacheDir());
    }
    
    private void clearApplicationCache(File cacheDir){
        if (cacheDir == null) {
            return;
        }

        File[] files = cacheDir.listFiles();
        try {
            for (File file : files) {
                if (file.isDirectory()) {
                    clearApplicationCache(file);
                } else {
                	file.delete();
                }
            }
        } catch(Exception e){
        	
        }
    }
}